package com.erp.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.order.mapper.ErpSellerChildOrderMapper;
import com.erp.order.mapper.ErpSellerOrderLogMapper;
import com.erp.order.mapper.ErpSellerOrderMapper;
import com.erp.order.mapper.ErpSellerOrderProductMapper;
import com.erp.order.service.IErpSellerOrderLogService;
import com.erp.order.service.PullOrderFromAeService;
import com.rabbitmq.client.Channel;
import com.ruoyi.ae.api.domain.AeStoreChildOrder;
import com.ruoyi.ae.api.domain.AeStoreOrder;
import com.ruoyi.ae.api.domain.AeStoreOrderProduct;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.ruoyi.gather.api.RemoteCollectAbsentSkuService;
import com.ruoyi.gather.api.RemoteCollectProductService;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.gather.api.domain.ErpCollectAbsentSku;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import com.ruoyi.order.api.domain.ErpSellerChildOrder;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerOrderLog;
import com.ruoyi.order.api.domain.ErpSellerOrderProduct;
import com.ruoyi.system.api.RemoteSysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 拉取AE新订单监听
 * @Author: j.zh
 * @Date: 2024/5/2
 * @Version: 4.0.0
 **/
@Slf4j
@Component
@RabbitListener(queues = "pull.incremental.order.queue", ackMode = "MANUAL")
public class PullIncrementalOrderFromAeListener {

    @Resource
    ErpSellerOrderMapper erpSellerOrderMapper;
    @Resource
    IErpSellerOrderLogService erpSellerOrderLogService;
    @Resource
    ErpSellerOrderLogMapper erpSellerOrderLogMapper;
    @Resource
    PullOrderFromAeService pullOrderFromAeService;

    private static Map<String, Object> orderStatusTacticsMap = OrderProcessFlag.getOrderStatusCollocationMap();
    String statusStr = "WAIT_BUYER_ACCEPT_GOODS,PLACE_ORDER_SUCCESS,WAIT_SELLER_SEND_GOODS,FINISH,RISK_CONTROL";
    String inProcessOrderStatus = "103,1031,105,106,1061,1071,1072,1073,1074,108,109,115";

    /**
     * 拉取AE新订单
     *
     * @param info
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(String info, Channel channel, Message message) throws IOException {

        try {
            log.debug("=============接收消息，消息队列开始执行（拉取处理增量订单）");
            // 回复队列消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 将JSON字符串转换为Map
            JSONObject divideJson = JSONObject.parseObject(info);
            Map<String, Object> divideMap = (Map<String, Object>) divideJson;
            divide(divideMap);
        } catch (Exception e) {
            // TODO 消费异常，设置入库操作

            System.out.println("=============执行异常：" + e.toString());
        }

    }


    /**
     * @param divideMap
     * @Description: 新订单入库
     * @Author: j.zh
     * @Date: 2024/5/2
     * @Version: 4.0.0
     **/
    @Transactional
    public R<Object> divide(Map<String, Object> divideMap) {
        Integer type = (Integer) divideMap.get("type");
        ErpSellerOrder newOrder = pullOrderFromAeService.encapsulationErpOrder(divideMap);
        // 保存订单至ERP
        //循环该订单
        Map<String, Object> map = new HashMap<>();
        //若已存在，则进入增量订单方法 TODO 增量订单用其他方式更新
        ErpSellerOrder erpSellerOrderSel = erpSellerOrderMapper.queryOrderByOrderId(newOrder.getOrderId());
        newOrder.setId(erpSellerOrderSel.getId());
        if (erpSellerOrderSel.getErpInnerOrderStatus().equals("114")) {
            return R.fail("订单状态为114，不需要变更");
        }

        if (erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Evaluation.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Error.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.MySelf.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Out.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.CompanyEva.getInfo())
                || erpSellerOrderSel.getOrderProcessFlag().equals(OrderProcessFlag.Invalid.getInfo())) {
            //测评单和作废单不再更新状态
            return R.fail("订单流程代码不需要继续更新状态");
        }
        map = disposeIncrementalOrders(newOrder, erpSellerOrderSel);
        if (Objects.isNull(map)) {
//                    OrderLogType orderLogType = OrderLogType.CancelOrder;
//                    erpSellerOrderLogService.createOrderLog(order.getOrderId(), null, orderLogType, null, OrderProcessFlag.Problem.getInfo(), "701");
            return R.fail("不存在");
        }
        newOrder = (ErpSellerOrder) map.get("order");

        newOrder.setUpdateTime(new Date());

        //处理订单数据
        OrderLogType orderLogType = (OrderLogType) map.get("orderLogType");
        String remark = (String) map.get("remark");
        String orderProcessFlag = (String) map.get("orderProcessFlag");
        String erpInnerOrderStatus = (String) map.get("erpInnerOrderStatus");
        if (orderLogType != null) {
            //当日志类型不为空时，再生成日志
            //处理map，生成日志
            erpSellerOrderLogService.createOrderLog(newOrder.getOrderId(), null, orderLogType, remark, orderProcessFlag, erpInnerOrderStatus);
        }
        return R.ok();
    }


    /**
     * 处理增量订单
     *
     * @param order
     * @param erpSellerOrderSel
     * @return
     */
    public Map<String, Object> disposeIncrementalOrders(ErpSellerOrder order, ErpSellerOrder erpSellerOrderSel) {
        Map<String, Object> map = new HashMap<>();
        //判断订单类型
        String orderProcessFlag = null;
        OrderLogType orderLogType = null;
        String remark = null;

        //erp内部状态
        String erpOrderStatus = erpSellerOrderSel.getErpInnerOrderStatus();
        //erp当前速卖通状态
        String nowOrderStatus = erpSellerOrderSel.getOrderStatus();
        //速卖通当前速卖通状态
        String newOrderStatus = order.getOrderStatus();

        ErpSellerOrderLog lastOrderLog = new ErpSellerOrderLog();

        //订单状态策略
//        Map<String, Object> orderStatusTacticsMap;
//        System.out.println(orderStatusTacticsMap);
        String prbNowStatus = nowOrderStatus;
        String prbNewStatus = newOrderStatus;
        if (!statusStr.contains(nowOrderStatus)) {
            prbNowStatus = "PROBLEM";
        }
        if (!statusStr.contains(newOrderStatus)) {
            prbNewStatus = "PROBLEM";
        }
        //订单组合
        String orderTactics = prbNowStatus + "-" + prbNewStatus;
//        System.out.println(orderTactics);
        //获取对应策略
        String tactics = (String) orderStatusTacticsMap.get(orderTactics);
        System.out.println(order.getOrderId() + ":" + orderTactics);
        if (tactics == null) {
            return null;
        }
        switch (tactics) {
            case "100":
                //正常流程，流程代码不变
                break;
            case "101":
                //流程代码不变，状态变为101 未付款-待发货 风控-待发货
                erpOrderStatus = "101";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.WaitSellerSendGoods;
//                findOrderReceiptInfo(order.getOrderId());

                //TODO 暂时屏蔽 设置商品的编辑类型
//                List<ErpSellerChildOrder> childOrders = erpSellerChildOrderMapper.selectList(
//                        new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, order.getOrderId())
//                );
//                if (childOrders.size() > 0) {
//                    List<String> skuCodeList = childOrders.stream()
//                            .map(ErpSellerChildOrder::getSkuCode)    // 抽出每个ErpSellerStoreProductGroup对象的id
//                            .collect(Collectors.toList());   // 创建新的集合
//                    for (String skuCode : skuCodeList) {
//                        iErpCollectProductService.setProToOrder(skuCode);
//                    }
//                }
                break;
            case "102":
                //流程代码不变，状态变为102 未付款-封控
                erpOrderStatus = "102";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.RiskControlOrder;
                break;
            case "103":
                //流程代码变为problem,状态变为107 未付款，封控，待发货-已发货
                erpOrderStatus = "107";
                orderProcessFlag = OrderProcessFlag.Problem.getInfo();
                orderLogType = OrderLogType.OrderTurnProblemForSendGoodsOK;
                break;
            case "104":
                if (inProcessOrderStatus.contains(erpSellerOrderSel.getErpInnerOrderStatus())) {
                    //订单在采购流程中结束
                    //流程代码变为异常,状态不变
                    erpOrderStatus = erpSellerOrderSel.getErpInnerOrderStatus();
                    orderProcessFlag = OrderProcessFlag.Error.getInfo();
                    orderLogType = OrderLogType.inTheProcessOrderErrorFinish;
                    remark = "disposeIncrementalOrders";
                } else {
                    erpOrderStatus = "114";
                    orderProcessFlag = erpSellerOrderSel.getOrderProcessFlag();
                    orderLogType = OrderLogType.OrderTurnFinish;
                }
                break;
            case "105":
                //流程代码变为problem,状态变为701
                erpOrderStatus = "701";
                orderProcessFlag = OrderProcessFlag.Problem.getInfo();
                orderLogType = OrderLogType.OrderTurnProblem;
                remark = pullOrderFromAeService.problemRemark(newOrderStatus);
                break;
            case "106":
                //PROBLEM 问题件转待付款 PLACE_ORDER_SUCCESS
                erpOrderStatus = "100";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.ProblemOrderTurnPlaceOrder;
                break;
            case "107":
                //问题件转风控
                erpOrderStatus = "102";
                orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                orderLogType = OrderLogType.ProblemOrderTurnRiskControlOrder;
                break;
            case "108":
                //问题件转待发货 流程代码往上，有没有菜鸟、线下、测评、自发货的订单，如果有则流程代码返回上一层级701-对应状态。如果没有，则流程代码不变，701-101
                lastOrderLog = pullOrderFromAeService.findLastOrderLog(order.getOrderId());
                if (lastOrderLog != null) {
                    erpOrderStatus = lastOrderLog.getPreviousStatus();
                    orderProcessFlag = lastOrderLog.getPreviousOrderProcess();
                    orderLogType = OrderLogType.ProblemOrderTurnLastProcessOrder;
                } else {
                    erpOrderStatus = "101";
                    orderProcessFlag = OrderProcessFlag.Begin.getInfo();
                    orderLogType = OrderLogType.ProblemOrderTurnSendGoodsOrder;
                }
                break;
            case "109":
                //问题件转已发货 流程代码往上找，有没有菜鸟、线下、测评、自发、作废、截单的订单，如果有则流程代码返回上一层级701-107。如果没有，则流程代码不变，701-107
                lastOrderLog = pullOrderFromAeService.findLastOrderLog(order.getOrderId());
                orderLogType = OrderLogType.ProblemOrderTurnSendGoodsOKOrder;
                if (lastOrderLog != null) {
                    orderProcessFlag = lastOrderLog.getPreviousOrderProcess();
                    orderLogType = OrderLogType.ProblemOrderTurnLastProcessOrder;
                }
                erpOrderStatus = "107";
                break;
            case "110":
                //问题件转已完成
                orderProcessFlag = OrderProcessFlag.Problem.getInfo();
                orderLogType = OrderLogType.ProblemOrderTurnFinishOrder;
                erpOrderStatus = "114";
                break;
            case "111":
                //问题件变问题件，流程代码仍为problem，但remark可能要更新
                lastOrderLog = pullOrderFromAeService.findLastOrderLog(order.getOrderId());
                //上个问题件的异常原因
                remark = pullOrderFromAeService.problemRemark(lastOrderLog.getRemark());
                //本次异常原因
                String nowRemark = pullOrderFromAeService.problemRemark(newOrderStatus);
                //进行比对
                if (!nowRemark.equals(remark)) {
                    //获取最开始时的问题件转化信息
                    orderProcessFlag = OrderProcessFlag.Problem.getInfo();
                    erpOrderStatus = "701";
                    orderLogType = OrderLogType.NewProblem;
                }
                break;
            case "112":
                //已发货变为已完成
//                if (inProcessOrderStatus.contains(erpSellerOrderSel.getErpInnerOrderStatus())) {
//                    //订单在采购流程中结束
//                    //流程代码变为异常,状态不变
//                    erpOrderStatus = erpSellerOrderSel.getErpInnerOrderStatus();
//                    orderProcessFlag = OrderProcessFlag.Error.getInfo();
//                    orderLogType = OrderLogType.inTheProcessOrderErrorFinish;
//                } else {
                //流程代码变为problem,状态变为114
                erpOrderStatus = "114";
                orderProcessFlag = erpSellerOrderSel.getOrderProcessFlag();
                orderLogType = OrderLogType.OrderTurnFinish;
//                }
                break;
        }

        //若订单是测评单或作废单，则订单后续流程应不变

        order.setOrderProcessFlag(orderProcessFlag);
        order.setErpInnerOrderStatus(erpOrderStatus);

        map.put("orderLogType", orderLogType);
        map.put("remark", remark);
        map.put("orderProcessFlag", orderProcessFlag);
        map.put("erpInnerOrderStatus", erpOrderStatus);

        map.put("order", order);
        map.put("erpOrderStatus", erpOrderStatus);
        return map;
    }

}
